package com.fang.aop;

import com.fang.annotations.Limiting;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Fang Ruichuan
 * @date 2022-12-27 10:08
 */
@Slf4j
@Aspect
@Component
public class RateLimiterAspect {
    private ConcurrentHashMap<String, RateLimiter> RATE_LIMITERS = new ConcurrentHashMap<>();
    private RateLimiter rateLimiter;

    @Pointcut("@annotation(com.fang.annotations.Limiting)")
    public void serviceLimit() {

    }

    @Around("serviceLimit()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        // 获取拦截的方法名
        Signature signature = point.getSignature();
        // 获取拦截的方法名
        MethodSignature msig = (MethodSignature) signature;
        // 返回被织入增加处理目标对象
        Object target = point.getTarget();
        // 为了获取注解信息
        Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
        // 获取注解信息
        Limiting annotation = currentMethod.getAnnotation(Limiting.class);
        // 获取注解每秒加入桶中的token
        double limitNum = annotation.limitNum();
        // 注解所在方法名区分不同的限流策略
        String functionName = msig.getName();

        if (RATE_LIMITERS.containsKey(functionName)) {
            rateLimiter = RATE_LIMITERS.get(functionName);
        } else {
            RATE_LIMITERS.put(functionName, RateLimiter.create(limitNum));
            rateLimiter = RATE_LIMITERS.get(functionName);
        }
        if (rateLimiter.tryAcquire()) {
            log.info("处理完成");
            return point.proceed();
        } else {
            throw new RuntimeException("服务器繁忙，请稍后再试...");
        }
    }


}
